package org.example.lotterysystem.service.impl;

import org.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import org.example.lotterysystem.common.exception.ServiceException;
import org.example.lotterysystem.common.util.*;
import org.example.lotterysystem.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author:  LiuTao
 * Version: 1.0
 * Date:    2025-04-07  16:57
 */
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    //验证码规范、过期时间、短信模版
    private static final String VERIFICATION_CODE_PREFIX = "VERIFICATION_CODE_";
    private static final Long VERIFICATION_CODE_EXPIRE = 60L;
    private static final String VERIFICATION_CODE_TEMPLATE_CODE = "SMS_154950909";

    @Autowired
    private SMSUtil smsUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void sendVerificationCode(String phoneNumber) {
        //检验手机号
        if(!RegexUtil.checkMobile(phoneNumber)){
           throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        //生成验证码
        String code = CaptchaUtil.getCaptcha(4);
        //发送验证码 格式：{"code" : code}
        Map<String, String> map = new HashMap<>();
        map.put("code", code);
        smsUtil.sendMessage(VERIFICATION_CODE_TEMPLATE_CODE, phoneNumber, JacksonUtil.writeValueAsString(map));
        //缓存验证码
        redisUtil.set(VERIFICATION_CODE_PREFIX + phoneNumber, code, VERIFICATION_CODE_EXPIRE);
    }

    @Override
    public String getVerificationCode(String phoneNumber) {
        //检验验证码
        if(!RegexUtil.checkMobile(phoneNumber)){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        return redisUtil.get(VERIFICATION_CODE_PREFIX + phoneNumber);
    }
}
